<template>
  <!-- style="width: 500px" -->
  <div>
    <n-card
      class="cardStyle"
      title="注册"
      :bordered="false"
      size="huge"
      role="dialog"
      aria-modal="true"
      @close="store.hideLogin"
    >
      <template #header-extra> </template>
      <n-form
        :model="form"
        :rules="rules"
        label-placement="left"
        label-width="auto"
        ref="formRef"
        @keyup.enter="handleConfirm"
      >
        <n-form-item path="username">
          <n-input
            v-model:value="form.username"
            class="input"
            block
            placeholder="请输入用户名"
          >
            <template #prefix>
              <n-icon :component="PersonOutline" />
            </template>
          </n-input>
        </n-form-item>
        <n-form-item path="password">
          <n-input
            type="password"
            class="input"
            block
            placeholder="请输入密码"
            v-model:value="form.password"
            clearable
          >
            <template #prefix>
              <n-icon :component="LockClosedOutline" />
            </template>
          </n-input>
        </n-form-item>
        <div class="mail-wrapper">
          <n-form-item style="flex: 1; margin-right: 12px" path="email">
            <n-input
              v-model:value="form.email"
              clearable
              class="input"
              block
              placeholder="请输入邮箱"
            >
              <template #prefix>
                <n-icon :component="Mail" />
              </template>
            </n-input>
          </n-form-item>
          <n-button
            :disabled="emailDuration != 0 || !emailValid"
            type="primary"
            secondary
            size="large"
            @click="sendEmail"
            >{{
              emailDuration != 0 ? `${emailDuration}S` : "发送邮件"
            }}</n-button
          >
          <!-- <div @click="getSvgverify" class="capcha">
            <div v-html="capchaData"></div>
          </div> -->
        </div>
        <n-form-item v-show="emailValid" path="mailId">
          <n-input
            type="text"
            class="input"
            block
            placeholder="请输入邮箱验证码"
            v-model:value="form.mailId"
            clearable
          >
            <template #prefix>
              <n-icon :component="LockClosedOutline" />
            </template>
          </n-input>
        </n-form-item>
        <div class="capcha-wrapper">
          <n-form-item path="verifyCode">
            <n-input
              v-model:value="form.verifyCode"
              clearable
              class="input"
              block
              placeholder="请输入验证码"
            >
              <template #prefix>
                <n-icon :component="PrismOutline" />
              </template>
            </n-input>
          </n-form-item>

          <div @click="getSvgverify" class="capcha">
            <div v-html="capchaData"></div>
          </div>
        </div>
      </n-form>

      <n-space> </n-space>
      <template #footer>
        <n-button
          @click="handleConfirm"
          class="login-button"
          type="success"
          strong
          secondary
          style="width: 100%"
          :loading="loginLoading"
          >注册</n-button
        >
        <div class="mention">登录即同意《所有条款》</div>
      </template>
    </n-card>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch, onUnmounted, computed } from "vue";
import { useMainStore } from "../../store/index";
import { useUserStore } from "@/store/user";
import { useRouter } from "vue-router";
import {
  FlashOutline,
  PersonCircleOutline,
  PersonOutline,
  LockClosedOutline,
  PrismOutline,
  Mail,
} from "@vicons/ionicons5";
import { getVerity, logIN, registerEmailApi, sendEmailApi } from "@/api";
import { FormItemRule, useMessage } from "naive-ui";
const formRef = ref();
const message = useMessage();
const store = useMainStore();
const userStore = useUserStore();
const loginLoading = ref(false);
const router = useRouter();
const emailDuration = ref(0);
// const emailValid = ref(false);
let timer: any;
// 验证码
const getSvgverify = async () => {
  const { data }: any = await getVerity(40, 150);
  console.log(data);
  capchaData.value = data.data;
  form.value.captchaId = data.capchaId;
  form.value.verifyCode = "";
  // getverity.value = data.data
  // loginForm.value.captchaId = data.captchaId
};
const form = ref({
  username: "",
  password: "",
  verifyCode: "",
  captchaId: "",
  email: "",
  mailId: "",
});
const capchaData = ref("");
// watch(
//   () => form.value.mail,
//   () => {}
// );
const emailValid = computed(() => {
  return isValidEmail(form.value.email);
});
const rules = {
  username: {
    required: true,
    trigger: ["blur", "input"],
    // message: "请输入用户名",
    validator(rule: FormItemRule, value: string) {
      if (!value) {
        return new Error("请输入用户名");
      } else if (value.indexOf(" ") != -1) {
        return new Error("用户名称里不允许有空格");
      } else if (value.length > 15) {
        return new Error("用户名称字符不能超出15个");
      }
      return true;
    },
  },
  password: {
    required: true,
    trigger: ["blur", "input"],
    validator(rule: FormItemRule, value: string) {
      if (!value) {
        return new Error("请输入密码");
      } else if (value.indexOf(" ") != -1) {
        return new Error("密码里不允许有空格");
      } else if (value.length > 15) {
        return new Error("密码长度不超出15个字符");
      } else if (value.length < 6) {
        return new Error("密码长度不小于6个字符");
      }
      return true;
    },
  },
  verifyCode: {
    required: true,
    trigger: ["blur", "input"],
    validator(rule: FormItemRule, value: string) {
      if (!value) {
        return new Error("请输入验证码");
      } else if (value.indexOf(" ") != -1) {
        return new Error("验证码里不允许有空格");
      } else if (value.length != 4) {
        return new Error("验证码长度应该是4个字符");
      }
      return true;
    },
  },
};
const handleConfirm = async () => {
  const validRes = await formRef.value.validate();
  console.log(validRes);
  loginLoading.value = true;
  registerEmailApi(form.value)
    .then((res: any) => {
      console.log(res);
      message.success("注册成功");
      localStorage.setItem("token", res.data);
      userStore.updateUserInfo();
    })
    .catch((e) => {
      message.error(e);
      console.log(e);
    })
    .finally(() => {
      loginLoading.value = false;
    });
};
function isValidEmail(email) {
  // 定义邮箱的正则表达式
  const regex =
    /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  // 使用正则表达式的test方法检查邮箱是否合法
  return regex.test(email.toLowerCase());
}

const sendEmail = () => {
  emailDuration.value = 60;
  sendEmailApi(form.value.email)
    .then((res) => {
      message.success("邮件发送成功，请查收");

      timer = setInterval(() => {
        emailDuration.value -= 1;
        if (emailDuration.value < 0) {
          emailDuration.value = 0;
          clearInterval(timer);
        }
      }, 1000);
    })
    .catch((e) => {
      console.log(e);
      message.error(`邮件发送失败:${e}`);
      emailDuration.value = 0;
    });
};

onMounted(() => {
  getSvgverify();
});
onUnmounted(() => {
  clearInterval(timer);
});
</script>

<style lang="scss" scoped>
.cardStyle {
  width: 500px;
}
.input {
  height: 40px;
  line-height: 40px;
}
.capcha-wrapper {
  display: flex;
}
.mail-wrapper {
  display: flex;
  justify-content: space-between;
}
.capcha {
  width: 180px;
  height: 40px;
  margin-left: 12px;
  cursor: pointer;
  border-radius: 4px;
  svg {
    height: 100%;
    width: 100%;
    position: relative;
  }
}
.login-button {
  width: 80px;
}
.mention {
  margin-top: 12px;
  font-size: 12px;
  cursor: pointer;
  user-select: none;
}
.mention:hover {
  font-weight: bold;
}
.mention:active {
  opacity: 0.8;
}
@media (max-width: 830px) {
  .cardStyle {
    width: 90vw;
  }
  :deep(.n-card > .n-card__content) {
    padding: 0px;
  }
}
</style>
